<template>
  <div class="table-container">
    <div class="table-header">
      <h4>{{ title }}</h4>
      <div class="table-actions">
        <el-button size="small" @click="refreshTable">刷新</el-button>
        <el-button size="small" @click="$emit('edit')">编辑</el-button>
      </div>
    </div>
    
    <div class="table-content">
      <el-table 
        :data="displayData" 
        stripe 
        border
        size="small"
        height="100%"
        :empty-text="emptyText">
        
        <el-table-column 
          v-for="column in tableColumns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :formatter="column.formatter"
          show-overflow-tooltip>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div v-if="showPagination" class="table-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '数据表格'
  },
  data: {
    type: Array,
    default: () => []
  },
  config: {
    type: Object,
    default: () => ({
      columns: [],
      pageSize: 20,
      showPagination: true
    })
  }
})

const emit = defineEmits(['edit'])

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(props.config.pageSize || 20)

// 计算属性
const tableColumns = computed(() => {
  if (!props.data.length) return []
  
  // 如果配置了列，使用配置的列
  if (props.config.columns && props.config.columns.length > 0) {
    return props.config.columns.map(columnId => {
      const sampleData = props.data[0]
      return {
        prop: columnId,
        label: getColumnLabel(columnId),
        width: getColumnWidth(columnId, sampleData[columnId]),
        formatter: getColumnFormatter(columnId, sampleData[columnId])
      }
    })
  }
  
  // 否则自动生成所有列
  const sampleData = props.data[0]
  return Object.keys(sampleData).map(key => ({
    prop: key,
    label: getColumnLabel(key),
    width: getColumnWidth(key, sampleData[key]),
    formatter: getColumnFormatter(key, sampleData[key])
  }))
})

const totalCount = computed(() => props.data.length)

const showPagination = computed(() => {
  return props.config.showPagination !== false && totalCount.value > pageSize.value
})

const displayData = computed(() => {
  if (!showPagination.value) {
    return props.data
  }
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return props.data.slice(start, end)
})

const emptyText = computed(() => {
  return props.data.length === 0 ? '暂无数据' : '没有匹配的数据'
})

// 方法
const getColumnLabel = (columnId) => {
  // 这里可以从字段定义中获取更友好的标签
  const labelMap = {
    id: 'ID',
    name: '姓名',
    age: '年龄',
    department: '部门',
    salary: '薪资',
    city: '城市',
    date: '日期'
  }
  return labelMap[columnId] || columnId
}

const getColumnWidth = (columnId, sampleValue) => {
  // 根据数据类型和内容长度自动计算列宽
  if (typeof sampleValue === 'number') {
    return 120
  }
  if (typeof sampleValue === 'string') {
    if (sampleValue.length > 20) return 200
    if (sampleValue.length > 10) return 150
    return 120
  }
  return 150
}

const getColumnFormatter = (columnId, sampleValue) => {
  // 根据数据类型返回格式化函数
  if (columnId === 'salary') {
    return (row, column, cellValue) => {
      return cellValue ? `¥${cellValue.toLocaleString()}` : '-'
    }
  }
  
  if (columnId === 'date') {
    return (row, column, cellValue) => {
      if (!cellValue) return '-'
      const date = new Date(cellValue)
      return date.toLocaleDateString('zh-CN')
    }
  }
  
  if (typeof sampleValue === 'number') {
    return (row, column, cellValue) => {
      return cellValue ? cellValue.toLocaleString() : '-'
    }
  }
  
  return null
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const refreshTable = () => {
  console.log('刷新表格数据')
  // 这里可以实现数据刷新逻辑
}

// 监听数据变化，重置分页
watch(() => props.data, () => {
  currentPage.value = 1
}, { deep: true })
</script>

<style scoped>
.table-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.table-header h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-content {
  flex: 1;
  padding: 16px;
  overflow: hidden;
}

.table-pagination {
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}

/* 自定义表格样式 */
:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table--border) {
  border: 1px solid #e4e7ed;
}

:deep(.el-table--border th) {
  border-right: 1px solid #e4e7ed;
}

:deep(.el-table--border td) {
  border-right: 1px solid #e4e7ed;
}
</style>